package com.hmall.user.interceptor;

import com.hmall.user.utils.UserHolder;

import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserInterceptor implements HandlerInterceptor {

    //在业务处理器处理请求之前被调用
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //拿到请求头
        String authorization = request.getHeader("authorization");
        //判断是否空
        if (StringUtils.isBlank(authorization)) {
            throw new RuntimeException("未登录");
        }
        //拿到存入线程
        Long user = Long.valueOf(authorization);
        UserHolder.setUser(user);
        return true;
    }

    //在业务处理器处理请求执行完成后
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    //在DispatcherServlet完全处理完请求后被调用，可用于清理资源等
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清空
        UserHolder.removeUser();
    }
}
